<?php


namespace app\finance\controller;


use app\base\BaseController;
use think\facade\Db;
use think\facade\View;

class SaleTarget extends BaseController
{
    protected $title='销售目标';
    protected $table='sale_target';
    protected $tableMx='sale_target_detail';

    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['st.status','>',-1];

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['st.status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['st.name|d.title|ad.name','like','%'.$this->param['name'].'%'];
            }
            if (isset($this->param['years'])&&$this->param['years']){
                $where[]=['st.years','=',$this->param['years']];
            }
            if (isset($this->param['create_time'])&&$this->param['create_time']){
                $dates1=explode('~',$this->param['create_time']);
                $b_time=strtotime($dates1[0]);
                $e_time=strtotime($dates1[1].' 23:59:59');
                $where[]=['st.create_time','between',[$b_time,$e_time]];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->alias('st')
                ->leftJoin('department d','d.id=st.groupId')
                ->leftJoin('admin ad','ad.id=st.createId')
                ->where($where)
                ->field('st.*,d.title as groupName,ad.name as createName')
                ->order('st.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param=$this->param;
        $id=$param['id']??0;
        if ($this->request->post()){

            if (!$param['groupId']){
                return  to_assign(1,'参数缺失');
            }
            $mx=$param['mx']??[];

            if (!$mx){
                return  to_assign(1,'请添加团队人员');
            }
            unset($param['mx']);
            $adminIds=$mx['adminId']??[];
            $dTargets=$mx['dTargets']??[];
            $count=0;
            foreach ($dTargets as $dt){
                $count+=$dt;
            }
            if ($count!=$param['targets']){
                return  to_assign(1,'团队目标填写有误');
            }
            $param['update_time'] = time();
            unset($param['id']);
            try {
                if ($id){
                    add_log('edit', $id, $this->param,$this->title);
                    Db::name($this->table)->where('id',$id)->update($param);
                    Db::name($this->tableMx)->where('orderId',$id)->update(['status'=>-1,'deleted'=>time(),'update_time'=>time()]);
                }else{
                    $param['createId']=$this->uid;
                    $param['departId']=$this->did;
                    $param['create_time'] = time();
                    $id=Db::name($this->table)->insertGetId($param);
                    add_log('add', $id, $this->param,$this->title);
                }
                $mxData=[];
                foreach ($adminIds as $k=>$v){
                    $mxData[]=[
                        'orderId'=>$id,
                        'adminId'=>$adminIds[$k],
                        'dTargets'=>$dTargets[$k],
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                }
                Db::name($this->tableMx)->insertAll($mxData);

            }catch (\Exception $e){
                return to_assign(1,'操作失败：'.$e->getMessage());
            }
            return  to_assign();

        }else{
            $departList=Db::name('department')->where('status',1)->field('id,title as name')->select();
            $detail=[];
            $mxList=[];
            if ($id){
                $detail=Db::name($this->table)->where('id',$id)->find();
                $mxList=Db::name($this->tableMx)
                    ->alias('std')
                    ->leftJoin('admin ad','ad.id=std.adminId')
                    ->where('std.status','>',-1)
                    ->where('std.orderId',$id)
                    ->field('std.*,ad.name as userName')
                    ->select();
            }
            View::assign('departList',$departList);
            View::assign('detail',$detail);
            View::assign('mxList',$mxList);
            View::assign('id',$id);
            return view('form');
        }
    }

    public function delete()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id','in',$ids)->column('status');
        if (in_array(2,$status)){
            return to_assign(1,'参数有误');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            Db::name($this->tableMx)->where('orderId','in',$ids)->where('status','>',-1)
                ->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $mx=Db::name($this->tableMx)->where('status',1)
            ->where('orderId',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>2,
                'update_time'=>time()]);
            Db::name($this->tableMx)->where('status',1)
                ->where('orderId',$id)->update([
                    'status'=>2,
                    'update_time'=>time()]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
}